import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Alert,
  ActivityIndicator,
  TouchableOpacity,
  Modal,
  RefreshControl,
  Dimensions,
  PermissionsAndroid,
  Platform,
} from 'react-native';
import CardList from '../components/CardList';
import { Card, CreateCardRequest, UpdateCardRequest } from '../types/Card';
import CardApiNative from '../services/CardApiNative';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { useLayoutEffect } from 'react';
import AddCardScreen from './AddCardScreen';

// 应用状态枚举
enum AppState {
  INITIALIZING = 'initializing',
  REQUESTING_PERMISSION = 'requesting_permission',
  LOADING = 'loading',
  READY = 'ready',
  ERROR = 'error',
  REFRESHING = 'refreshing',
}

const { width } = Dimensions.get('window');
const isTablet = width >= 768;

const MainScreen: React.FC = () => {
  const [cards, setCards] = useState<Card[]>([]);
  const [appState, setAppState] = useState<AppState>(AppState.INITIALIZING);
  const [error, setError] = useState<string | null>(null);
  const [editingCard, setEditingCard] = useState<Card | undefined>();
  const [saving, setSaving] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [isLoadingCards, setIsLoadingCards] = useState(false);
  const [lastLoadTime, setLastLoadTime] = useState(0);
  const navigation = useNavigation<any>();

  // 请求通知权限
  const requestNotificationPermission = useCallback(async (): Promise<boolean> => {
    try {
      if (Platform.OS === 'android' && Platform.Version >= 33) {
        console.log('🔐 请求通知权限...');
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
          {
            title: '通知权限',
            message: 'BabyTapMobile 需要通知权限来显示前台服务状态，确保服务在后台正常运行',
            buttonNeutral: '稍后询问',
            buttonNegative: '拒绝',
            buttonPositive: '允许',
          }
        );
        
        const hasPermission = granted === PermissionsAndroid.RESULTS.GRANTED;
        console.log('通知权限状态:', hasPermission ? '已授予' : '未授予');
        
        if (!hasPermission) {
          Alert.alert(
            '通知权限未授予',
            '前台服务可能无法正常工作。您可以在系统设置中手动启用通知权限。',
            [
              { text: '继续使用', style: 'default' },
              { text: '去设置', onPress: () => {
                // 这里可以添加跳转到应用设置的逻辑
                console.log('引导用户去设置');
              }}
            ]
          );
        }
        
        return hasPermission;
      } else {
        // Android 13 以下版本不需要特殊权限
        console.log('Android 13 以下版本，无需特殊通知权限');
        return true;
      }
    } catch (error) {
      console.error('请求通知权限失败:', error);
      return false;
    }
  }, []);

  // 初始化应用
  const initializeApp = useCallback(async () => {
    try {
      setAppState(AppState.INITIALIZING);
      console.log('🚀 初始化应用...');
      
      // 首先请求通知权限
      setAppState(AppState.REQUESTING_PERMISSION);
      const hasPermission = await requestNotificationPermission();
      console.log('权限请求完成，权限状态:', hasPermission);
      
      // 启动 API 服务器
      setAppState(AppState.LOADING);
      await startApiServer();
      
      // 加载卡片数据
      await loadCards();
      
      setAppState(AppState.READY);
      console.log('✅ 应用初始化完成');
    } catch (error) {
      console.error('❌ 应用初始化失败:', error);
      setError(error instanceof Error ? error.message : '初始化失败');
      setAppState(AppState.ERROR);
    }
  }, [requestNotificationPermission]);

  useEffect(() => {
    initializeApp();
  }, [initializeApp]);

  // 每次进入页面时加载一次数据
  useFocusEffect(
    React.useCallback(() => {
      if (appState === AppState.READY) {
        console.log('📱 页面获得焦点，加载卡片数据');
        // 直接调用 API，避免依赖 loadCards 函数
        handlePageFocusLoad();
      }
    }, [appState])
  );

  useLayoutEffect(() => {
    navigation.setOptions({
              headerRight: () => (
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <TouchableOpacity onPress={handleSendUDPBroadcast} style={{ marginRight: 16 }}>
              <Text style={{ fontSize: 20, color: '#4a90e2', fontWeight: 'bold' }}>📡</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={handleSettings} style={{ marginRight: 16 }}>
              <Text style={{ fontSize: 20, color: '#4a90e2', fontWeight: 'bold' }}>⚙️</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={handleAddCard} style={{ marginRight: 8 }}>
              <Text style={{ fontSize: 24, color: '#4a90e2', fontWeight: 'bold' }}>＋</Text>
            </TouchableOpacity>
          </View>
        ),
    });
  }, [navigation]);

  const startApiServer = useCallback(async () => {
    try {
      console.log('启动 API 服务器...');
      await CardApiNative.startApiServer();
      console.log('✅ API 服务器启动成功');
    } catch (error) {
      console.error('❌ 启动 API 服务器失败:', error);
      throw new Error('API 服务器启动失败');
    }
  }, []);

  const loadCards = useCallback(async (forceRefresh = false) => {
    // 防止重复请求
    if (isLoadingCards) {
      console.log('⏳ 正在加载中，跳过重复请求');
      return;
    }

    try {
      console.log('🚀 初始化加载卡片...');
      setIsLoadingCards(true);
      setLastLoadTime(Date.now());
      
      if (!forceRefresh) {
        setAppState(AppState.LOADING);
      }
      setError(null);
      
      const cardsData = await CardApiNative.getCards();
      console.log('✅ 初始化卡片数据获取成功:', cardsData);
      
      // 验证数据格式
      if (!Array.isArray(cardsData)) {
        throw new Error('卡片数据格式错误');
      }
      
      setCards(cardsData);
      setAppState(AppState.READY);
    } catch (error) {
      console.error('❌ 初始化加载卡片失败:', error);
      const errorMessage = error instanceof Error ? error.message : '加载卡片失败';
      setError(errorMessage);
      setAppState(AppState.ERROR);
      
      if (error instanceof Error) {
        console.error('错误信息:', error.message);
        if ((error as any).stack) {
          console.error('错误堆栈:', (error as any).stack);
        }
      }
    } finally {
      setIsLoadingCards(false);
    }
  }, [isLoadingCards]);

  const handleRefresh = useCallback(async () => {
    try {
      setRefreshing(true);
      await loadCards(true); // 强制刷新
    } finally {
      setRefreshing(false);
    }
  }, [loadCards]);

  const handleCardPress = useCallback((card: Card) => {
    Alert.alert(
      card.title,
      `正面图片: ${card.front_image}\n\n背面文字: ${card.back_text}`,
      [{ text: '确定' }]
    );
  }, []);

  const handleEditPress = useCallback((card: Card) => {
    navigation.navigate('AddCard', { card });
  }, [navigation]);

  const handleDeletePress = useCallback((card: Card) => {
    Alert.alert(
      '确认删除',
      `确定要删除卡片"${card.title}"吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => deleteCard(card.id),
        },
      ]
    );
  }, []);

  const deleteCard = useCallback(async (id: number) => {
    try {
      setSaving(true);
      await CardApiNative.deleteCard(id);
      setCards(prevCards => prevCards.filter(card => card.id !== id));
      Alert.alert('成功', '卡片删除成功');
    } catch (error) {
      console.error('Failed to delete card:', error);
      Alert.alert('错误', '删除卡片失败');
    } finally {
      setSaving(false);
    }
  }, []);

  const handleAddCard = useCallback(() => {
    navigation.navigate('AddCard');
  }, [navigation]);

  const handleSettings = useCallback(() => {
    navigation.navigate('ServerInfo');
  }, [navigation]);

  const handleSendUDPBroadcast = useCallback(async () => {
    try {
      console.log('📡 开始发送UDP广播...');
      const result = await CardApiNative.sendUDPBroadcast();
      Alert.alert('UDP广播发送成功', '请在局域网设备打开 宝宝点读卡电视版 查看');
    } catch (error) {
      console.error('❌ 发送UDP广播失败:', error);
      Alert.alert('错误', '发送UDP广播失败: ' + (error instanceof Error ? error.message : String(error)));
    }
  }, []);

  const handleRetry = useCallback(() => {
    initializeApp();
  }, [initializeApp]);

  // 页面获得焦点时的加载函数
  const handlePageFocusLoad = useCallback(async () => {
    // 防抖机制：3秒内不重复请求
    const now = Date.now();
    if (now - lastLoadTime < 3000) {
      console.log('⏳ 页面焦点加载：请求过于频繁，跳过');
      return;
    }

    // 防止重复请求
    if (isLoadingCards) {
      console.log('⏳ 页面焦点加载：正在加载中，跳过');
      return;
    }

    try {
      console.log('📱 页面焦点加载：开始加载卡片...');
      setIsLoadingCards(true);
      setLastLoadTime(now);
      setError(null);
      
      const cardsData = await CardApiNative.getCards();
      console.log('📱 页面焦点加载：卡片数据获取成功:', cardsData);
      
      // 验证数据格式
      if (!Array.isArray(cardsData)) {
        throw new Error('卡片数据格式错误');
      }
      
      setCards(cardsData);
    } catch (error) {
      console.error('📱 页面焦点加载：加载卡片失败:', error);
      const errorMessage = error instanceof Error ? error.message : '加载卡片失败';
      setError(errorMessage);
    } finally {
      setIsLoadingCards(false);
    }
  }, [lastLoadTime, isLoadingCards]);

  // 使用 useMemo 缓存卡片列表
  const sortedCards = useMemo(() => {
    return [...cards].sort((a, b) => {
      // 按创建时间倒序排列
      if (a.id && b.id) {
        return b.id - a.id;
      }
      return 0;
    });
  }, [cards]);

  // 渲染加载状态
  if (appState === AppState.INITIALIZING || appState === AppState.REQUESTING_PERMISSION || appState === AppState.LOADING) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4a90e2" />
        <Text style={styles.loadingText}>
          {appState === AppState.INITIALIZING && '正在初始化...'}
          {appState === AppState.REQUESTING_PERMISSION && '正在请求通知权限...'}
          {appState === AppState.LOADING && '正在启动服务...'}
        </Text>
      </View>
    );
  }

  // 渲染错误状态
  if (appState === AppState.ERROR) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorIcon}>⚠️</Text>
        <Text style={styles.errorTitle}>加载失败</Text>
        <Text style={styles.errorMessage}>{error}</Text>
        <TouchableOpacity style={styles.retryButton} onPress={handleRetry}>
          <Text style={styles.retryButtonText}>重试</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* 卡片列表 */}
      <View style={styles.content}>
        <CardList
          cards={sortedCards}
          onCardPress={handleCardPress}
          onEditPress={handleEditPress}
          onDeletePress={handleDeletePress}
          refreshing={refreshing}
          onRefresh={handleRefresh}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  loadingText: {
    color: '#666',
    fontSize: isTablet ? 18 : 16,
    marginTop: 16,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  errorIcon: {
    fontSize: isTablet ? 64 : 48,
    marginBottom: 16,
  },
  errorTitle: {
    fontSize: isTablet ? 24 : 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  errorMessage: {
    fontSize: isTablet ? 16 : 14,
    color: '#666',
    textAlign: 'center',
    marginBottom: 24,
    lineHeight: isTablet ? 24 : 20,
  },
  retryButton: {
    backgroundColor: '#4a90e2',
    paddingHorizontal: isTablet ? 32 : 24,
    paddingVertical: isTablet ? 16 : 12,
    borderRadius: 8,
  },
  retryButtonText: {
    color: '#ffffff',
    fontSize: isTablet ? 18 : 16,
    fontWeight: 'bold',
  },
  header: {
    backgroundColor: '#4a90e2',
    paddingTop: 50,
    paddingBottom: 20,
    paddingHorizontal: 20,
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#ffffff',
    textAlign: 'center',
  },
  headerSubtitle: {
    fontSize: 14,
    color: '#ffffff',
    textAlign: 'center',
    marginTop: 4,
    opacity: 0.8,
  },
  content: {
    flex: 1,
  },
  addButton: {
    backgroundColor: '#4a90e2',
    margin: 20,
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  addButtonText: {
    color: '#ffffff',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default MainScreen; 